/***

    KunGang - Simple Video Editor
    Copyright (C) 2020  SUmoon.com

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
***/

#include "effectmgr.h"

#include <QGridLayout>
#include <QLabel>
#include <QDialogButtonBox>
#include <QLineEdit>
#include <QFileDialog>
#include <QPushButton>
#include <QMessageBox>
#include <QDebug>
#include <QSignalMapper>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QNetworkConfigurationManager>
#include <QStandardPaths>


#include "project/proxygenerator.h"
#include "project/footage.h"
#include "ui/mainwindow.h"
#include "global/global.h"
#include "global/path.h"
#include "global/config.h"
#include "effects/effectloaders.h"
#include "quazip/JlCompress.h"

EffectMgrDialog::EffectMgrDialog(QWidget *parent) :
  QDialog(parent)
{
  HIDE_DIALOG_QUESTION_MARK
  setWindowTitle(tr("Effect Manager"));
  line = 0;
  //bool showRecents = true;
  //bool showNewProj = false;
 // set up dialog's layout
  this->setFixedWidth(400);

  QGridLayout* layout = new QGridLayout(this);
  effectname_edit = new QLineEdit(this);
  effectname_edit->setPlaceholderText(tr("input code to download"));
  layout->addWidget(effectname_edit,line, 0,1,3);
  load_btn = new QPushButton(tr("Get Effect"),this);
  connect(load_btn, SIGNAL(clicked(bool)),this, SLOT(load_effect()));
  layout->addWidget(load_btn, line,3,1,1);
  line ++;
  progressBar = new QProgressBar(this);
  //progressBar->setFormat("%p% (ETA: 0:00:00)");
  progressBar->setEnabled(false);
  progressBar->setRange(0,100);
  progressBar->setValue(0);
  layout->addWidget(progressBar,line, 0,1,3);  
  info = new QLabel("",this);
  layout->addWidget(info, line, 3,1,1);
  line ++;
  
  QPushButton*  closebtn = new QPushButton(tr("Get Effect"),this);
  connect(closebtn, SIGNAL(clicked(bool)),this, SLOT(reject()));
  closebtn->setText(tr("Close"));
  layout->addWidget(closebtn, line, 1, 1, 1);

  QLabel* link = new QLabel("<a href=\"http://www.sumoon.com/kgeffects/\">获取特效下载码</a>",this);
  layout->addWidget(link, line, 2,1,2);
  
  connect(link,SIGNAL(linkActivated(QString)), olive::Global.get(),SLOT(openUrl(QString)));
 
}

void EffectMgrDialog::load_effect()
{
  QString fn = effectname_edit->text();

  if(!fn.isEmpty())
  {
    info->setText(tr("downloading..."));
    QString effectUrl = QString("http://imgs.sumoon.com/effects/%1.zip").arg(fn);
    QNetworkAccessManager* manager = new QNetworkAccessManager();
    
    connect(manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(finished_slot(QNetworkReply *)));
    connect(manager, SIGNAL(finished(QNetworkReply *)), manager, SLOT(deleteLater()));
    
    QUrl url(effectUrl);
    QNetworkRequest request(url);
    QNetworkReply*  reply = manager->get(request);
    if(reply && reply->error() == QNetworkReply::NoError)
    {
      connect(reply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(updateDataReadProgress(qint64,qint64)));
    }
    else
    {
      info->setText(tr("Network error"));
    }
    
  }
}
void EffectMgrDialog::updateDataReadProgress(qint64 s, qint64 total)
{
    if(total == 0)
    {
      info->setText(tr("Network error"));
      return;
    }

    int value = 100*s/total;
    progressBar->setValue(value);

}
void EffectMgrDialog::finished_slot(QNetworkReply *reply)
{
  if(reply == nullptr)
  {
    info->setText(tr("No network"));
    return;
  }
#if defined(Q_OS_LINUX)
  QString writablePath = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
#else
  QString writablePath = get_app_path(); 
#endif
  QDir dir(writablePath);
  
  if(!dir.mkpath(writablePath))
  {
    info->setText(tr("Cannot create Dir"));
    return;
  }
  dir.mkdir("kg_effects");
#if defined(Q_OS_LINUX)
  //cp common verts if not exist /linux
  dir.cd("kg_effects"); 
  if(!dir.exists("common.vert"))
  {
     QDir appDir(get_app_path());
     appDir.cd("kg_effects"); 
     QFile f(appDir.filePath("common.vert"));
     f.copy(dir.filePath("common.vert"));
     QFile f2(appDir.filePath("common.frag"));
     f2.copy(dir.filePath("common.frag"));
  }
  dir.cdUp();
#endif
  QByteArray data = reply->readAll();
  QString tmpFile = dir.filePath("neweffect.zip");
  QFile *file = new QFile(tmpFile, this);
  if (file && !file->open(QIODevice::WriteOnly)) {
    qInfo() << "Write file error! " << file->errorString() << "\n";
    info->setText(tr("Write file error"));
    return;
  }
  
  if(file && !data.isEmpty())
  {
    int writeBytes = file->write(data);
    file->flush();
    file->close();
    if (writeBytes != data.size()) {
      qInfo() << "Write file error:" <<  file->errorString() << "\n";
      info->setText(tr("Write file error"));
      return;
    }
    else
    {
      info->setText(tr("extracting..."));
      QString destDir = dir.filePath("kg_effects");
      QStringList sl = JlCompress::extractDir(tmpFile, destDir);
      qInfo() << sl << "\n";
      if(sl.size() >= 1)
      {
        info->setText(tr("well done"));
        for(int i=0;i<sl.size();i++)
        {
          QString fi = sl[i];
          if(fi.endsWith(".xml"))
          {
            loadEffectFromFile(fi);
          }
        }
        QMessageBox::information(this, tr("Effect Manager"), tr("Effect has been downloaded successfully"));
      }
      else
      {
        info->setText(tr("invalid zip file"));

      }
    }
  }
}
void EffectMgrDialog::accept() {
 
  QDialog::accept();
}
